<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Helpers\ApiResponse;
use App\Model\AdminUser;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;

use Hyperf\Utils\Context;
use Phper666\JwtAuth\Exception\TokenValidException;
use Phper666\JwtAuth\Jwt;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RefreshTokenMiddleware implements MiddlewareInterface
{
    use ApiResponse;
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @var ContainerInterface
     */
    protected $container;


    /**
     * @var Jwt
     */
    protected $jwt;

    public function __construct(ContainerInterface $container,StdoutLoggerInterface $logger,Jwt $jwt)
    {
        $this->container = $container;

        $this->logger = $logger;

        $this->jwt = $jwt;
    }

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = $request->getHeader('Authorization');

        if ($token){
            $getParserData = $this->jwt->getParserData();

            if (is_array($getParserData) && !empty($getParserData)){

                if ($getParserData['guard'] == 'admin'){

                    $user = AdminUser::find($getParserData['id']);

                    $request = Context::override(ServerRequestInterface::class,function ()use ($request,$user){
                        return $request->withAttribute('user',$user);
                    });

                    return  $handler->handle($request);
                }

            }else{
                throw new TokenValidException('token error',401);
            }
        }

        throw new TokenValidException('token error',401);
    }
}